package com.bs.bszhsq.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.auth0.jwt.JWT;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bs.bszhsq.entity.Fix;
import com.bs.bszhsq.entity.Users;
import com.bs.bszhsq.exception.ServiceException;
import com.bs.bszhsq.service.IUsersService;
import com.bs.bszhsq.utils.MessageType;
import io.swagger.annotations.Api;
import org.springframework.web.bind.annotation.*;
import com.bs.bszhsq.utils.R;
import io.swagger.annotations.ApiOperation;
import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.bs.bszhsq.service.ICarportService;
import com.bs.bszhsq.entity.Carport;


import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

/**
 * <p>
 * 车位信息 前端控制器
 * </p>
 *
 * @author 章宇光
 * @since 2024-03-25
 */
@RestController
@RequestMapping("/carport")
@Api(tags = "车位管理接口")
        public class CarportController {
    //service注入
@Resource
private ICarportService carportService;
@Resource
private IUsersService usersService;


@PostMapping
@ApiOperation(value = "新增")
public R save(@RequestBody Carport carport){
        if (BeanUtil.isEmpty(carport)){
                throw new ServiceException("500","传入参数不完整！");
        }
        boolean save= carportService.save(carport);
        return R.write(save);
        }


@PostMapping("/delete")
@ApiOperation(value = "删除")
public R delete(@RequestBody Long id){
        boolean b=carportService.removeById(id);
        return R.write(b);
        }

@PostMapping("/update")
@ApiOperation(value = "修改")
public R update(@RequestBody Carport carport) {
        boolean update = carportService.updateById(carport);
        return R.write(update);
        }


@PostMapping("/deletebatch")
@ApiOperation(value = "批量删除")
public R deletebatch(@RequestBody List<Long> ids) {
        boolean b = carportService.removeByIds(ids);
        return R.write(b);
        }
@GetMapping("/showCar")
@ApiOperation(value = "未预定的车位")
public R showCar(){
        LambdaQueryWrapper<Carport> lqw=new LambdaQueryWrapper<>();
        lqw.eq(Carport::getStatus, MessageType.CART_NORESERVE.getCode());
        List<Carport> list = carportService.list(lqw);
        return R.success(list);
}


@GetMapping("/page")
@ApiOperation(value = "分页查询")
public R page(@RequestParam Integer pageNum, @RequestParam Integer pageSize,@RequestParam(defaultValue = "") String name) {
        IPage<Carport> page = new Page<>(pageNum, pageSize);
        QueryWrapper<Carport> qw = new QueryWrapper<>();
        if (!"".equals(name)) {
                qw.like("name", name);
        }
        qw.orderByDesc("id");
        IPage<Carport> fixIPage = carportService.page(page, qw);
        return R.success(fixIPage);
        }

        @GetMapping("/NoReservePage")
        @ApiOperation(value = "分页查询可预定车位")
        public R page(@RequestParam Integer pageNum, @RequestParam Integer pageSize) {
                IPage<Carport> page = new Page<>(pageNum, pageSize);
                QueryWrapper<Carport> qw = new QueryWrapper<>();
                qw.eq("status",MessageType.CART_NORESERVE.getCode());
                IPage<Carport> fixIPage = carportService.page(page, qw);
                return R.success(fixIPage);
        }


@GetMapping("/ReservePage")
@ApiOperation(value = "查看已预定的车位信息")
public R getPage(@RequestParam Integer pageNum, @RequestParam Integer pageSize,@RequestParam(defaultValue = "") Long id){
        IPage<Carport> page = new Page<>(pageNum, pageSize);
        QueryWrapper<Carport> qw=new QueryWrapper<>();
        if (!"".equals(id)){

                qw.eq("user_id",id);
        }
        qw.eq("status",MessageType.CART_ISRESERVE.getCode());
        IPage<Carport> page1 = carportService.page(page, qw);
        return R.success(page1);
}


        @GetMapping("/export")
        @ApiOperation(value = "报修信息导出")
        public R export(HttpServletResponse response) throws Exception {
                //先获取全部数据
                List<Carport> list = carportService.list();
                //写出到浏览器
                ExcelWriter writer = ExcelUtil.getWriter(true);
                //定义别名
                writer.addHeaderAlias("id","ID");
                writer.addHeaderAlias("numberId","车位编号");
                writer.addHeaderAlias("type","车位类别");
                writer.addHeaderAlias("area","车位区域");
                writer.addHeaderAlias("place","车位位置");
                writer.addHeaderAlias("status","车位状态");
                writer.addHeaderAlias("note","车位备注");
                writer.addHeaderAlias("price","车位价格");
                writer.addHeaderAlias("addtime","创建时间");

                //写入数据
                writer.write(list,true);
                //设置浏览器响应格式
                response.setContentType("application/vnd.ms-excel;charset=utf-8");
                String fileName = URLEncoder.encode("报修信息", "UTF-8");
//test.xls是弹出下载对话框的文件名，不能为中文，中文请自行编码
                response.setHeader("Content-Disposition","attachment;filename="+fileName+".xls");
                ServletOutputStream outputStream = response.getOutputStream();
                writer.flush(outputStream,true);
                outputStream.close();
                writer.close();
                return R.success();
        }

        @PostMapping("/import")
        @ApiOperation(value = "导入信息")
        public R imp(MultipartFile file) throws Exception{
                InputStream inputStream = file.getInputStream();
                ExcelReader reader = ExcelUtil.getReader(inputStream);
                Map<String,String> map=new HashMap<>();
                map.put("车位编号","numberId");
                map.put("车位类别","type");
                map.put("车位区域","area");
                map.put("车位位置","place");
                map.put("车位状态","status");
                map.put("车位备注","note");
                map.put("车位价格","price");
                reader.setHeaderAlias(map);
                List<Carport> carports = reader.readAll(Carport.class);
                for (Carport carport : carports) {
                        carport.setAddtime(LocalDateTime.now());
                }
                boolean b = carportService.saveBatch(carports);
                System.out.println("文件导入"+b);
                return R.write(b);
        }

        @PostMapping("/carMoney")
        @ApiOperation("计算停车费")
        public R getCarMoney(@RequestBody Carport carport) throws ParseException {
                SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd");
                if (StrUtil.isEmptyIfStr(carport.getStartEndDto())){
                       return R.err();
                }
                Date start = simpleDateFormat.parse(carport.getStartEndDto()[0]);
                Date end = simpleDateFormat.parse(carport.getStartEndDto()[1]);
                long betweenDay = DateUtil.betweenDay(start, end, false);
                double mul = NumberUtil.mul(betweenDay, (long) carport.getPrice());
        return R.success(mul);
        }

        @PostMapping("/updateCar")
        @ApiOperation(value = "保存预定")
        private R saveCar(@RequestBody Carport carport){
                if (StrUtil.isEmptyIfStr(carport.getStartEndDto())){
                        throw new ServiceException("500","请选择停车时间！");
                }
                HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
                String token = request.getHeader("token");
                String userId = JWT.decode(token).getAudience().get(0);
                Users users = usersService.getById(userId);
                carport.setUserId(users.getId());
                carport.setStartEnd(carport.getStartEndDto().toString());
                carport.setStatus(Integer.valueOf(MessageType.CART_ISRESERVE.getCode()));
                return R.write(carportService.updateById(carport));
        }
        @PostMapping("deleteCar")
        @ApiOperation(value = "取消预定")
        public R delete(@RequestBody Carport carport){

                return R.write(carportService.updateCar(carport.getId()));
        }


        }
